<template>
	<!-- 每日防火巡查记录表 -->
	<view class="files">
		<camera-com v-if="cameraIsShow" :isSave="true" @saveImg="saveImg" style="width: 100%;height: 100%;z-index: 9999;position: fixed;bottom: 0;left: 0;" />
		<view class="tabs">
			<fui-list bottomBorder title="巡查人员基本信息">
				<view class="tab">
					<fui-list-cell>
						<text>巡查人员</text>
						<text class="fui-text__explain">{{inspectionStaff.name}}</text>
					</fui-list-cell>

					<fui-list-cell>
						<text>巡查日期</text>
						<text class="fui-text__explain">{{inspectionStaff.data}}</text>
					</fui-list-cell>

					<!-- 	<fui-input label="电子巡查" readonly textAlign="right" @click="showTab=!showTab"
						placeholder="点击选择电子标签"></fui-input> -->


					<!-- 	<fui-input required label="标签编号" readonly textAlign="right" placeholder="请选择电子标签"
						v-model="tabItem.serialNumber"></fui-input> -->

					<fui-input required label="巡查时段" readonly textAlign="right" placeholder="" v-model="inspectionStaff.time"></fui-input>



					<!-- 			<fui-input required label="巡查部位" readonly textAlign="right" placeholder="请选择电子标签"
						v-model="tabItem.position"></fui-input>
						
					<fui-input   label="标签位置" readonly textAlign="right" placeholder="请选择电子标签"
						v-model="tabItem.address"></fui-input> -->

				</view>
			</fui-list>

			<fui-list bottomBorder title="用火、用电有无违章情况">
				<view class="tab">
					<fui-input required label="巡查情况" readonly textAlign="right" @click="onShow(fileInElectricity.id)" placeholder="请选择" v-model="fileInElectricity.situation"></fui-input>
					<fui-input label="处理内容" readonly></fui-input>
					<u--textarea v-model="fileInElectricity.content" placeholder="请输入内容" count maxlength="250"></u--textarea>
				</view>
			</fui-list>
			<fui-list bottomBorder title="安全出口、疏散通道是否畅通，有无锁闭；安全疏散指示标志、应急照明是否完好">
				<view class="tab">
					<fui-input required label="巡查情况" readonly textAlign="right" @click="onShow(safety.id)" placeholder="请选择" v-model="safety.situation"></fui-input>
					<fui-input label="处理内容" readonly></fui-input>
					<u--textarea v-model="safety.content" placeholder="请输入内容" count maxlength="250"></u--textarea>
				</view>
			</fui-list>
			<fui-list bottomBorder title="常闭式防火门是否处于关闭状态，防火卷帘下是否堆放物品">
				<view class="tab">
					<fui-input required label="巡查情况" readonly textAlign="right" placeholder="请选择" @click="onShow(fireDoor.id)" v-model="fireDoor.situation"></fui-input>
					<fui-input label="处理内容" readonly></fui-input>
					<u--textarea v-model="fireDoor.content" placeholder="请输入内容" count maxlength="250"></u--textarea>
				</view>
			</fui-list>
			<fui-list bottomBorder title="消防设施、器材是否在位、完整有效。消防安全标志标识是否完好清晰">
				<view class="tab">
					<fui-input required label="巡查情况" readonly textAlign="right" placeholder="请选择" @click="onShow(normallyClosed.id)" v-model="normallyClosed.situation"></fui-input>
					<fui-input label="处理内容" readonly></fui-input>
					<u--textarea v-model="normallyClosed.content" placeholder="请输入内容" count maxlength="250"></u--textarea>
				</view>
			</fui-list>
			<fui-list bottomBorder title="消防安全重点部位的人员在岗情况">
				<view class="tab">
					<fui-input required label="巡查情况" readonly textAlign="right" placeholder="请选择" @click="onShow(fireFightingFacilities.id)" v-model="fireFightingFacilities.situation"></fui-input>
					<fui-input label="处理内容" readonly></fui-input>
					<u--textarea v-model="fireFightingFacilities.content" placeholder="请输入内容" count maxlength="250"></u--textarea>
				</view>
			</fui-list>
			<fui-list bottomBorder title="其他消防安全情况">
				<view class="tab">
					<fui-input required label="巡查情况" readonly textAlign="right" placeholder="请选择" @click="onShow(fireSafety.id)" v-model="fireSafety.situation"></fui-input>
					<fui-input label="处理内容" readonly></fui-input>
					<u--textarea v-model="fireSafety.content" placeholder="请输入内容" count maxlength="250"></u--textarea>
				</view>
			</fui-list>
			<fui-list bottomBorder title="巡检图片情况">
				<!-- <button style="background: #49a0ff;color: #fff;padding: 20rpx 40rpx;border-radius: 6rpx">
					拍照
				</button> -->
				<view @click="showCamera" style="color: #49a0ff;padding: 20rpx 0;text-decoration: underline;">
					拍照
				</view>
				<view class="tab">
					<up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10"></up-upload>
				</view>
			</fui-list>
		</view>
		<view class="tab_ops">
			<view style="width: 100%; display: flex; justify-content: space-between;">
				<!-- <fui-button btnSize="small" >巡查人员签字</fui-button> -->
				<!-- <fui-button btnSize="small"  >安全主管签字</fui-button> -->
			</view>
			<view style="padding-top: 40rpx;">
				<!-- <fui-button @click="submitImg" type="success">提交cs</fui-button> -->
				<fui-button @click="submit" type="success">提交</fui-button>
			</view>
		</view>
		<view>
			<u-picker :previewFullImage="true" capture multiple deletable @confirm="onOps" @cancel="showOps = !showOps" :show="showOps" :columns="columns"></u-picker>
		</view>
		<view>
			<up-action-sheet @select="onTab" round="18" @close="showTab=!showTab" :actions="tabList" :closeOnClickOverlay="true" :closeOnClickAction="true" title="标签选择" :show="showTab"></up-action-sheet>
		</view>
	</view>

</template>

<script>
	// const ByUniPlugin = uni.requireNativePlugin('by-BYNFC-BYnfcModule')
	// const KJNFC = uni.requireNativePlugin('KJ-NFC');
	import cameraCom from '@/components/cameraCom/cameraCom.vue'
	import moment from "moment"
	import {
		BASE_IP
	} from '@/common/http/url.js'
	import tools from "@/tools/tools.js"
	import nfc from "../../../common/nfc"
	import index from "../../../uni_modules/uview-plus";
	export default {
		name: 'firePatrol',
		components: {
			cameraCom
		},
		data() {
			return {
				cameraIsShow: false,
				user: "",
				inspectionStaff: {
					name: "",
					data: "",
					time: "",
					electron: "",
					position: ""
				},
				fileInElectricity: {
					id: 1,
					situation: "正常",
					content: ""
				},
				safety: {
					id: 2,
					situation: "正常",
					content: ""
				},
				fireDoor: {
					id: 3,
					situation: "正常",
					content: ""
				},
				normallyClosed: {
					id: 4,
					situation: "正常",
					content: ""
				},
				fireFightingFacilities: {
					id: 5,
					situation: "正常",
					content: ""
				},
				fireSafety: {
					id: 6,
					situation: "正常",
					content: ""
				},
				showOps: false,
				columns: [
					['正常', '异常']
				],
				index: 0,
				regime: "",
				isSubmit: false,
				tag: "",
				text: '号标签',
				fileList1: [],
				showTab: false,
				tabLabels: "",
				tabList: [],
				tabItem: "",
				isGcode: false,
				preset: "",
				photoList: null,

			}


		},
		onShow() {


		},
		methods: {
			showCamera() {
				this.cameraIsShow = true
			},
			saveImg(imgList) {
				console.log(imgList)
				this.cameraIsShow = false
				let list = [];
				imgList.map(res => {
					list.push({ url: res.src })
				})
				console.log(list)
				this.fileList1 = list
			},
			onShow(id) {
				console.log(id)
				this.showOps = !this.showOps
				this.index = id
			},
			goTakePhoto() {
				uni.navigateTo({
					url: "/pagesWork/cameraCom/cameraCom?font=拍摄巡检照片"
				})
			},
			getPrall() { //获取预设功能对象数据
				let pralldata = uni.getStorageSync("pralldata")
				this.preset = pralldata
				// let user = uni.getStorageSync("user")
				// uni.showLoading({
				// 	title:"正在加载数据"
				// })
				// // console.log(user)
				// this.user = user
				// let url = BASE_IP + "pc/presetfunction/find/presetFunction"
				// uni.request({
				// 	header: {
				// 		"Authorization": user.token,
				// 	},
				// 	url: url,
				// 	success: (res) => {
				// 		uni.hideLoading()
				// 		if (res.statusCode == 200) {
				// 			this.preset = res.data
				// 			console.log(this.pralldata)
				// 			// uni.setStorageSync("pralldata", this.pralldata)
				// 		} else {
				// 			uni.showToast({
				// 				icon: "error",
				// 				title: "请求失败"
				// 			})
				// 		}
				// 	},
				// 	fail: (res) => {
				// 		uni.hideLoading()
				// 		// console.log("请求失败：", res)
				// 		uni.showToast({
				// 			icon: "error",
				// 			title: "请求失败"
				// 		})
				// 	}
				// })

				// let user = uni.getStorageSync("user")
				// let url = BASE_IP + "pc/presetfunction/find/presetFunction/" + user.unitId + "/" + user.uuid
				// uni.request({
				// 	header: {
				// 		"Authorization": user.token,
				// 	},
				// 	url: url,
				// 	success: (res) => {
				// 		this.preset = res.data
				// 	},
				// 	fail: (res) => {
				// 		// console.log("请求失败：", res)
				// 	}
				// })
			},
			onTab(res) {
				console.log(res)
				if (res.serialNumber == 0) {
					this.tabItem = ""
					let pralldata = uni.getStorageSync("pralldata")
					this.inspectionStaff.time = pralldata.operatingTimeStart + " - " + pralldata.operatingTimeEnd
					return
				}
				for (let index in this.tabLabels) {
					if (this.tabLabels[index].serialNumber == res.serialNumber) {
						this.tabItem = this.tabLabels[index]
					}
				}
				console.log(this.tabItem)
				this.inspectionStaff.electron = this.tabItem.serialNumber
				this.inspectionStaff.time = this.tabItem.inspectionPeriod
				this.inspectionStaff.position = this.tabItem.position
			},
			queryTab() {
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/tab/query/" + user.unitId
				uni.request({
					header: {
						"Authorization": user.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					url: url,
					method: "GET",
					success: (res) => {
						console.log(res)
						if (res.cookies == 500) {
							uni.showToast({
								title: "服务器出现问题",
								icon: "error"
							})
							return
						}
						if (res.cookies == 404) {
							uni.showToast({
								title: "获取数据失败",
								icon: "error"
							})
							return
						}
						if (res.statusCode == 200) {
							let ls = res.data
							this.tabLabels = ls
							for (let index in ls) {
								let item = {
									name: "",
									serialNumber: "",
									color: ""
								}
								item.name = ls[index].serialNumber + "号标签"
								item.serialNumber = ls[index].serialNumber
								this.tabList.push(item)
							}
							let item = {
								name: "",
								serialNumber: "",
								color: ""
							}

							item.name = "清除标签"
							item.serialNumber = 0
							item.color = "#FF2B2B"
							this.tabList.push(item)
						}
					},
					fail: () => {
						uni.showToast({
							title: "服务器出现问题",
							icon: "error"
						})
						return
					}
				})
			},
			submitImg(id) {
				let fileList = this.fileList1
				console.log("fileList：", fileList.length)
				if (fileList[0] != "") {
					console.log(fileList)
					let url = BASE_IP + "pc/iotFireAlarmRecord/upload/img/" + id
					fileList.forEach((itme, index) => {
						console.log(itme)
						let path = itme.url
						// let files = []
						//  files.push(path)
						this.uploadFilePromise(path, url)
						console.log(path)
					})
				}

			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {

				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				for (let index in lists) {
					let url = {
						url: lists[index].url
					}
					console.log(url)
					this.fileList1.push(url)
				}
				// let fileListLen = this[`fileList${event.name}`].length
				// lists.map((item) => {
				// 	this[`fileList${event.name}`].push({
				// 		...item,
				// 		status: 'uploading',
				// 		message: '上传中'
				// 	})
				// })

				// for (let i = 0; i < lists.length; i++) {
				// 	const result = await this.uploadFilePromise(lists[i].url)
				// 	let item = this[`fileList${event.name}`][fileListLen]
				// 	this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
				// 		status: 'success',
				// 		message: '',
				// 		url: result
				// 	}))
				// 	fileListLen++
				// }

			},
			uploadFilePromise(path, url) {
				return new Promise((resolve, reject) => {
					let user = uni.getStorageSync("user")
					console.log("path：", path)
					console.log("user：", user)
					let a = uni.uploadFile({
						header: {
							"Authorization": user.token,
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						url: url, // 仅为示例，非真实的接口地址
						filePath: path,
						// files : path,
						name: 'file',
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			/**
			 * 读取电子标签
			 */
			readNfc() {

				setTimeout(() => {

					if (uni.getSystemInfoSync().platform == 'android') {
						nfc.initNFC()
						nfc.readNFC((res) => {
							console.log(res)
							let d = res
							let data = JSON.parse(d)



							if (!data.serialNumber) {
								uni.showModal({
									title: "提示",
									content: "此标签数据不匹配",
									showCancel: false
								})
								return
							}

							let labels = uni.getStorageSync("labels")
							let fage = false
							this.tag = data
							console.log("开始读取unitId：", data.unitId)

							if (this.user.unitId != data.unitId) {
								fage = !fage
							}

							// let fage = false
							// for (let t in labels) {
							// 	if (labels[t].id == data.id) {
							// 		fage = !fage
							// 	}
							// }

							if (!fage) {
								uni.showModal({
									title: "提示",
									content: "单位无此标签",
									showCancel: false
								})
								return
							}
							this.tag = data
							this.inspectionStaff.electron = data.serialNumber
							this.inspectionStaff.time = data.inspectionPeriod
							this.inspectionStaff.position = data.position
							// console.log(data)

							setTimeout(() => {
								uni.showModal({
									title: "提示",
									content: "读取" + data
										.serialNumber +
										"号标签成功\n是否全部正常",
									cancelText: "否",
									confirmText: "是",
									success: (res) => {
										if (res.confirm) {
											uni.showLoading({
												title: "正在提交"
											})
											this.submit()
										}
									}
								})
							}, 800)
							if (res) {
								nfc.closeNFC()
							}
						})
					}
					if (uni.getSystemInfoSync().platform == 'ios') {
						let nfcData = this.beginSession()
						console.log("nfcData：", nfcData)
					}
				}, 500)

			},
			isSupportsNFCRead() {
				KJNFC.isSupportsNFCRead((res) => {
					console.log("isSupportsNFCRead：" + JSON.stringify(res))
				});
			},
			isSupportsNFCWrite() {
				KJNFC.isSupportsNFCWrite((res) => {
					console.log("isSupportsNFCWrite：" + JSON.stringify(res))
				});
			},
			beginSession() {
				/**
				 * ios11-ios12，只有读取，ios13及以上，有读与写
				 * */
				var dic = {
					"alertMessage": "准备扫描，请将标签贴近手机", //提示的信息
					"invalidateAfterFirstRead": false, //是否第一个NDEF标签读取成功后，会话将自动失效
				}
				KJNFC.beginSession(dic, (res) => {
					console.log(JSON.stringify(res));
					if (res.type == "beginSession") {
						console.log("开始：" + JSON.stringify(res))
					} else if (res.type == "readerSessionDidBecomeActive") { //ios13及以上才会回调
						console.log("开始完成：" + JSON.stringify(res))
					} else if (res.type == "didInvalidateWithError") {
						console.log("扫描失败：" + JSON.stringify(res))
						if (res.errorCode == 200) {
							console.log("取消扫描")
						} else if (res.errorCode == 201) {
							console.log("扫描超时")
						}
					} else if (res.type == "didDetectNDEFs") { //ios11-ios12,才会回调
						console.log("检测NDEF：" + JSON.stringify(res))
					} else if (res.type == "didDetectTags") { //从这里开始，某个环节失败，都不会往下执行，ios13及以上才会回调
						console.log("读取标签：" + JSON.stringify(res))
						var tags = res.tags; //返回读取到的所有标签，isAvailable-是否可用
						if (tags.length > 0) {
							var tagIndex = 0; //传tags数组的索引
							KJNFC.connectToTag({
								"tagIndex": tagIndex
							}, (res) => {
								console.log("连接到标签：" + JSON.stringify(res))
								if (res.result == true) {
									KJNFC.queryNDEFStatus({
										"tagIndex": tagIndex
									}, (res) => {
										console.log("查询NDEF状态：" + JSON.stringify(res))
										if (res.result == true) {
											var status = res
												.status; //NDEF状态 1-不允许NDEF读取和写入 2-可读写 3-只读
											if (status == 2 || status == 3) {
												KJNFC.readNDEF({
													"tagIndex": tagIndex
												}, (res) => {
													if (!res.result) {
														return
													}

													if (res.result) {
														this.invalidateSession()
													}
													//res.records
													console.log("读NDEF：" + JSON
														.stringify(
															res.records))

													let dataJson = JSON.parse(res
														.records[
															0].payload)

													console.log("读NDEF：" + dataJson
														.serialNumber)

													let labels = uni.getStorageSync(
														"labels")

													let fage = false
													this.tag = dataJson
													console.log("开始读取unitId：", dataJson
														.unitId)
													if (this.user.unitId != dataJson
														.unitId) {
														fage = !fage
													}

													// for (let t in labels) {
													// 	console.log("labels：",labels[t])
													// 	if (labels[t].id == dataJson
													// 		.id) {
													// 		fage = !fage
													// 	}
													// }

													if (!fage) {
														uni.showModal({
															title: "提示",
															content: "单位无此标签",
															showCancel: false
														})
														return
													}

													this.inspectionStaff.electron =
														dataJson
														.serialNumber
													this.inspectionStaff.time =
														dataJson
														.inspectionPeriod
													this.inspectionStaff.position =
														dataJson
														.position
													// console.log(data)

													setTimeout(() => {
														uni.showModal({
															title: "提示",
															content: "读取" +
																dataJson
																.serialNumber +
																"号标签成功\n是否全部正常",
															cancelText: "否",
															confirmText: "是",
															success: (
																res
															) => {
																if (res
																	.confirm
																) {
																	uni.showLoading({
																		title: "正在提交"
																	})



																	this.submit()
																}
															}
														})
													}, 800)
												});
											}
										}
									})
								}
							})
						}
					}
				});
			},
			restartPolling() {
				KJNFC.restartPolling((res) => { //ios13及以上支持
					console.log("restartPolling：" + JSON.stringify(res))
				});
			},
			invalidateSession() {
				KJNFC.invalidateSession((res) => {
					console.log("invalidateSession：" + JSON.stringify(res))
				});
			},
			setAlertMessage() {
				KJNFC.setAlertMessage({
					"alertMessage": ""
				}, (res) => {
					console.log("setAlertMessage：" + JSON.stringify(res))
				});
			},
			/**
			 * 
			 * @param {Object} path 转入要签字的路径
			 */
			onSignatures(path) {
				let user = uni.getStorageSync("user")
				if (user.signature == undefined || user.signature == null || user.signature == "") {
					uni.showModal({
						title: "提示",
						content: "用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
					return
				}
				let docPath = path
				// let url = BASE_IP + user.signature

				// this.nweUpSignatures(docPath,user.signature)
				tools.upSignatures(docPath, user.signature)
				// console.log(url)
				// let _this = this
				// uni.downloadFile({ //下载
				// 	url: url, //图片下载地址
				// 	success: res => {
				// 		if (res.statusCode === 200) {
				// 			uni.saveFile({
				// 				tempFilePath: res.tempFilePath,
				// 				success: (r) => {
				// 					console.log(r)
				// 					_this.upSignatures(r.savedFilePath, docPath)
				// 				}
				// 			})
				// 		}
				// 	}
				// });
			},
			nweUpSignatures(pdfPath, sealPath) {
				console.log("=====pdf", pdfPath)
				console.log("=====seal", sealPath)
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/regulatory/update/pdf/signature"
				uni.request({
					header: {
						"Authorization": user.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					url: url,
					data: {
						imgPath: sealPath,
						pdfPath: pdfPath
					},
					success: (res) => {
						console.log(res)
						if (res.statusCode == 200) {
							uni.showToast({
								title: "签字成功",
								icon: "success"
							})
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: "签字失败",
								icon: "error"
							})
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "签字失败",
								icon: "error"
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: "签字失败",
							icon: "error"
						})
					}
				})
			},
			/** 签字函数
			 * @param {Object} filePath 签字图片
			 * @param {Object} docPath  要签字的文档
			 */
			upSignatures(filePath, docPath) {
				console.log(filePath, docPath)
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/regulatory/signature/word"
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					name: "file",
					url: url,
					formData: {
						"unitId": user.unitId,
						"path": docPath
					},
					filePath: filePath,
					success: (res) => {
						if (res.statusCode == 500) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
							return
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "上传失败,请重试",
							icon: "error"
						})
					}
				})
			},
			/**
			 * 盖章
			 * @param {Object} path 转入要盖章的文件路径
			 */
			onSeal(path) {

				let pralldata = uni.getStorageSync("pralldata")
				// console.log(pralldata)
				let docPath = path
				if (pralldata.unitFireSeal == "" || pralldata.unitFireSeal == undefined) {
					uni.showModal({
						title: "提示",
						content: "单位未上传消防专用章",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								return
							}
						}
					})
					return
				}

				// this.newUpLoadSeal(path,pralldata.unitFireSeal)
				tools.upLoadSeal(path, pralldata.unitFireSeal)

				// let url = BASE_IP + pralldata.unitFireSeal
				// console.log(url)
				// uni.downloadFile({ //下载
				// 	url: url, //图片下载地址
				// 	success: res => {
				// 		if (res.statusCode === 200) {
				// 			uni.saveFile({
				// 				tempFilePath: res.tempFilePath,
				// 				success: (r) => {
				// 					// console.log(r)
				// 					this.upLoadSeal(r.savedFilePath, docPath)
				// 				}
				// 			})
				// 		}
				// 	}
				// });
			},
			newUpLoadSeal(pdfPath, sealPath) {
				console.log("=====pdf", pdfPath)
				console.log("=====seal", sealPath)
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/regulatory/update/pdf/seal"
				uni.request({
					header: {
						"Authorization": user.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					url: url,
					data: {
						imgPath: sealPath,
						pdfPath: pdfPath
					},
					success: (res) => {
						console.log(res)
						if (res.statusCode == 200) {
							uni.showToast({
								title: "盖章成功",
								icon: "success"
							})
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: "盖章失败",
								icon: "error"
							})
						}
						if (res.statusCode == 500) {
							uni.showToast({
								title: "盖章失败",
								icon: "error"
							})
						}
					},
					fail: () => {
						uni.showToast({
							title: "盖章失败",
							icon: "error"
						})
					}
				})
			},
			/** 盖章函数
			 * @param {Object} filePath 印章图片
			 * @param {Object} docPath  要盖章的文档
			 */
			upLoadSeal(filePath, docPath) {
				let user = uni.getStorageSync("user")
				let url = BASE_IP + "pc/regulatory/update/word"
				uni.uploadFile({
					header: {
						"Authorization": user.token,
					},
					name: "file",
					url: url,
					formData: {
						"unitId": user.unitId,
						"path": docPath
					},
					filePath: filePath,
					success: (res) => {
						// console.log(res)
						if (res.statusCode == 500) {
							uni.showToast({
								title: "盖章失败",
								icon: "error"
							})
							return
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: "盖章失败",
								icon: "error"
							})
							return
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "盖章失败,请重试",
							icon: "error"
						})
					}
				})
			},
			init() {
				uni.showModal({
					title: "提示",
					content: "是否全部正常",
					confirmText: "是",
					cancelText: "否",
					success: (res) => {
						if (res.cancel) {
							// this.fireSafety.situation = ""
							// this.fireFightingFacilities.situation = ""
							// this.normallyClosed.situation = ""
							// this.fileInElectricity.situation = ""
							// this.safety.situation = ""
							// this.fireDoor.situation = ""
						}
						if (res.confirm) {
							uni.showLoading({
								title: "正在提交"
							})
							this.submit()
						}
					}
				})
			},
			onOps(res) {
				// console.log(res)
				switch (this.index) {
					case 1: {
						// console.log("=================")
						this.fileInElectricity.situation = res.value[0]
						break
					}
					case 2: {
						// console.log("=================")
						this.safety.situation = res.value[0]
						break
					}
					case 3: {
						// console.log("=================")
						this.fireDoor.situation = res.value[0]
						break
					}
					case 4: {
						// console.log("=================")
						this.normallyClosed.situation = res.value[0]
						break
					}
					case 5: {
						// console.log("=================")
						this.fireFightingFacilities.situation = res.value[0]
						break
					}
					case 6: {
						// console.log("=================")
						this.fireSafety.situation = res.value[0]
						break
					}
					default: {

					}
				}
				this.showOps = !this.showOps
			},

			async submitHead() {
				if (this.tabItem != "") {
					console.log(1);
					if (this.tabItem.watermarkImgState == 1) {
						console.log(2);
						console.log("fileList1：", this.fileList1.length);
						if (this.fileList1.length < 1) {
							console.log(3);
							uni.showToast({
								title: "请上传水印巡查图片",
								icon: "error"
							});
							return;
						}
					}
					if (this.tabItem.preciseLocation == 1) {
						console.log("精确定位")
						try {
							const res = await new Promise((resolve, reject) => {
								uni.getLocation({
									highAccuracyExpireTime: 3000,
									accuracy: "10m",
									altitude: true,
									success: resolve,
									fail: reject
								});
							});
							console.log(res);
							let lon = res.longitude;
							let lat = res.latitude;
							await this.distance(lon, lat, this.tabItem.longitude, this.tabItem.latitude);
							console.log(this.isGcode);
						} catch (err) {
							// console.error("获取位置失败:", err);
							// uni.showToast({
							// 	title: "无法获取当前位置",
							// 	icon: "error"
							// });
						}
					} else {
						console.log("模糊定位")
						try {
							const res = await new Promise((resolve, reject) => {
								uni.getLocation({
									altitude: false,
									success: resolve,
									fail: reject
								});
							});
							console.log(res);
							let lon = res.longitude;
							let lat = res.latitude;
							await this.distance(lon, lat, this.tabItem.longitude, this.tabItem.latitude);
							console.log(this.isGcode);
						} catch (err) {
							// console.error("获取位置失败:", err);
							// uni.showToast({
							// 	title: "无法获取当前位置",
							// 	icon: "error"
							// });
						}
					}
				}
			},
			/** 距离测量
			 * @param {Number} lon1 出发地经度
			 * @param {Number} lat1 出发地纬度
			 * @param {Number} lon2 目的地经度
			 * @param {Number} lat2 目的地纬度
			 */
			distance(lon1, lat1, lon2, lat2) {
				let url = BASE_IP + "pc/map/distance/" + lon1 + "/" + lat1 + "/" + lon2 + "/" + lat2 + "/" + this.tabItem
					.preciseLocation;
				console.log("distanceUrl：", url);
				let user = uni.getStorageSync("user");
				return new Promise((resolve, reject) => {
					uni.request({
						header: {
							"Authorization": user.token,
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						url: url,
						method: "GET",
						success: (res) => {
							console.log(res);
							if (res.statusCode == 200) {
								if (res.data.code == 0) {
									uni.showToast({
										title: res.data.msg,
										icon: "error"
									});
									reject(res.data.msg); // 如果请求失败，拒绝Promise
								} else {
									let jdata = JSON.parse(res.data.data);
									if (jdata.gcode == 0) {

										reject("需要前往指定位置"); // 如果gcode为0，拒绝Promise
									} else {
										this.isGcode = true;
										resolve(); // 成功时解析Promise
									}
								}
							} else {
								uni.showToast({
									title: "服务器出现问题",
									icon: "error"
								});
								reject("服务器出现问题"); // 如果状态码不是200，拒绝Promise
							}
						},
						fail: () => {
							uni.showToast({
								title: "请求失败",
								icon: "error"
							});
							reject("请求失败"); // 请求失败时拒绝Promise
						}
					});
				});
			},
			submit() {
				this.submitHead()
				if (this.tabItem != null && this.tabItem != "" && this.tabItem != undefined) {
					if (!this.isGcode) {
						uni.showModal({
							showCancel: false,
							title: "提示",
							content: "请前往" + this.tabItem.serialNumber + "号标签的位置"
						});
						return
					}
				}

				if (this.isSubmit) {
					uni.showToast({
						title: "请勿重复提交",
						icon: "error"
					})
					return
				}
				if (this.fileInElectricity.situation == "") {
					uni.showToast({
						title: "表单未填写完整",
						icon: "error"
					})
					return
				}
				if (this.safety.situation == "") {
					uni.showToast({
						title: "表单未填写完整",
						icon: "error"
					})
					return
				}
				if (this.normallyClosed.situation == "") {
					uni.showToast({
						title: "表单未填写完整",
						icon: "error"
					})
					return
				}
				if (this.fireFightingFacilities.situation == "") {
					uni.showToast({
						title: "表单未填写完整",
						icon: "error"
					})
					return
				}
				if (this.fireDoor.situation == "") {
					uni.showToast({
						title: "表单未填写完整",
						icon: "error"
					})
					return
				}
				if (this.fireSafety.situation == "") {
					uni.showToast({
						title: "表单未填写完整",
						icon: "error"
					})
					return
				}



				let json1 = {
					date: this.inspectionStaff.data,
					timeQuantum: this.inspectionStaff.time,
					eSignature: this.inspectionStaff.name,
					inspectionSituation1: this.fileInElectricity.situation,
					inspectionSituation2: this.safety.situation,
					inspectionSituation3: this.normallyClosed.situation,
					inspectionSituation4: this.fireFightingFacilities.situation,
					inspectionSituation5: this.fireDoor.situation,
					inspectionSituation6: this.fireSafety.situation,

					handingInformation1: this.fileInElectricity.content,
					handingInformation2: this.safety.content,
					handingInformation3: this.normallyClosed.content,
					handingInformation4: this.fireFightingFacilities.content,
					handingInformation5: this.fireDoor.content,
					handingInformation6: this.fireSafety.content,
				}
				if (json1.inspectionSituation1 == "异常") {
					if (json1.handingInformation1 == "") {
						uni.showModal({
							title: "提示",
							content: "用火、用电有无违章情况异常\n请填写处理内容",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									return
								}
							}
						})
						return
					}
				}

				if (json1.inspectionSituation2 == "异常") {
					if (json1.handingInformation2 == "") {
						uni.showModal({
							title: "提示",
							content: "安全出口、疏散通道是否畅通，有无锁闭;安全疏散指示标志、应急照明是否完好情况异常\n请填写处理内容",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									return
								}
							}
						})
						return
					}
				}

				if (json1.inspectionSituation3 == "异常") {
					if (json1.handingInformation3 == "") {
						uni.showModal({
							title: "提示",
							content: "消防设施、器材是否在位、完整有效。消防安全标志标识是否完好清晰情况异常\n请填写处理内容",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									return
								}
							}
						})
						return
					}
				}

				if (json1.inspectionSituation4 == "异常") {
					if (json1.handingInformation4 == "") {
						uni.showModal({
							title: "提示",
							content: "消防安全重点部位的人员在岗情况异常\n请填写处理内容",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									return
								}
							}
						})
						return
					}
				}


				if (json1.inspectionSituation5 == "异常") {
					if (json1.handingInformation5 == "") {
						uni.showModal({
							title: "提示",
							content: "常闭式防火门是否处于关闭状态，防火卷帘下是否堆放物品情况异常\n请填写处理内容",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {

									return
								}
							}
						})
						return
					}
				}
				if (json1.inspectionSituation6 == "异常") {
					if (json1.handingInformation6 == "") {
						uni.showModal({
							title: "提示",
							content: "其他消防安全情况异常\n请填写处理内容",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									return
								}
							}
						})
						return
					}
				}
				let flag_storage = true
				let user = uni.getStorageSync("user")
				if (user.signature == "" || user.signature == undefined || user.signature == null) {
					uni.showModal({
						title: "提示",
						content: "用户未上传签名请前往“预设功能-添加操作员-输入账号-添加签名”，如果已添加操作员上传签名即可",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								flag_storage = false
								uni.navigateTo({
									url: "/pagesWork/preinstall/preinstall"
								})
								return
							}
						}
					})
					return
				}

				if (!flag_storage) {
					return
				}

				let pralldata = this.preset
				console.log(pralldata)
				let falg_seal = true
				if (pralldata.unitFireSeal == "" || pralldata.unitFireSeal == undefined) {
					uni.showModal({
						title: "提示",
						content: "单位未上传消防专用章,请前往“预设功能-单位消防专用章”上传",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								falg_seal = false
								uni.navigateTo({
									url: "/pages/preinstall/preinstall"
								})
								return
							}
						}
					})
					return
				}

				if (!falg_seal) {
					return
				}


				console.log(json1)
				let url = BASE_IP + "pc/record/record/inspection"
				let classifyId = this.regime.classifyId
				// console.log(this.regime)
				// let user = uni.getStorageSync("user")
				uni.showLoading({
					title: "正在提交"
				})

				this.isSubmit = !this.isSubmit
				uni.request({
					url: url,
					header: {
						"Authorization": user.token,
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					data: {
						unitId: user.unitId,
						name: user.nickName,
						classifyId: classifyId,
						json: JSON.stringify(json1),
						uuid: user.uuid
					},
					method: "POST",
					success: (res) => {
						console.log("提交结果：", res)
						if (res.statusCode == 200) {
							uni.showToast({
								title: "上传成功",
								icon: "success"
							})
							// this.onSeal(res.data.path)
							setTimeout(() => {
								// this.onSignatures(res.data.path)
								this.setTab()
								this.submitImg(res.data.id)
							}, 500)
							// setTimeout(() => {
							// 	this.submitImg(res.data.id)
							// }, 800)
							setTimeout((r) => {
								console.log(res)
								uni.navigateBack({
									delta: 1,
									success: function() {
										const pages = getCurrentPages(); //获取当前页面栈
										const prevPage = pages[pages.length -
											1]; //获取上一个页面实例对象
										prevPage.getCollapseDatas(); //调用上一个页面的onLoad方法
									}
								});
							}, 1500)
							return
						}

						if (res.statusCode == 500) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
							this.isSubmit = !this.isSubmit
							return
						}
						if (res.statusCode == 404) {
							uni.showToast({
								title: "上传失败",
								icon: "error"
							})
							this.isSubmit = !this.isSubmit
							return
						}
					},
					fail: (res) => {
						uni.showToast({
							title: "上传失败",
							icon: "error"
						})
						this.isSubmit = !this.isSubmit
					}
				})
			},
			setTab() {
				if (this.isGcode) {
					let url = BASE_IP + "pc/tab/up/writeTime/" + this.tabItem.id + "/" + this.inspectionStaff.data
					console.log("url：", url)
					let user = uni.getStorageSync("user")
					uni.request({
						header: {
							"Authorization": user.token,
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						url: url,
						method: "POST",
						success: (res) => {
							// console.log("test=>>>>>>",res)
						}
					})
				}
			}
		},
		onLoad(ops) {
			uni.setNavigationBarTitle({
				title: "每日防火巡查记录表"
			})
			this.queryTab()
			this.getPrall()
			// setTimeout(() => {
			// 	this.init()
			// }, 800)

			let user = uni.getStorageSync("user")
			// console.log(user)
			// console.log(ops.regime)
			this.regime = JSON.parse(ops.regime)
			this.inspectionStaff.name = user.nickName
			const currentDate = moment();
			const year = currentDate.year();
			const month = currentDate.month() + 1;
			const day = currentDate.date();

			this.inspectionStaff.data = year + "-" + month + "-" + day



			let pralldata = uni.getStorageSync("pralldata")
			this.inspectionStaff.time = pralldata.operatingTimeStart + " - " + pralldata.operatingTimeEnd
			if (!this.tabLabels) {
				setTimeout(() => {
					uni.showModal({
						title: "提示",
						content: "是否全部正常",
						cancelText: "否",
						confirmText: "是",
						success: (res) => {
							if (res.confirm) {
								this.submit()
							}
						}
					})
				}, 500)
			} else {
				setTimeout(() => {
					uni.showModal({
						title: "提示",
						content: "是否选择电子标签",
						cancelText: "否",
						confirmText: "是",
						success: (res) => {
							if (res.confirm) {
								// this.readNfc()
								this.showTab = !this.showTab
								// if (!this.tabLabels) {
								// 	uni.showToast({
								// 		title: "此单位无标签",
								// 		icon: "error"
								// 	})
								// 	return
								// }
								// console.log(this.tabLabels)
							}
						}
					})
				}, 500)
			}


			// console.log(pralldata)

			// this.inspectionStaff.time = pralldata.operatingTimeStart + " - " + pralldata.operatingTimeEnd

		}
	}
</script>

<style>
	page {
		background-color: #F1F4FA;
	}

	.tabs {
		width: 95%;
		margin: auto;
	}

	.tab {
		width: 100%;
		background-color: white;
		border-radius: 8px;
		/* margin: auto; */
		box-shadow: 1px 1px 10px #DCDFE6;
		padding-top: 10rpx;
		padding-bottom: 20rpx;
	}

	.fui-text__explain {
		font-size: 14px;
		color: #606266;
	}

	.tab_ops {
		padding: 40rpx;
		padding: 40rpx;
	}
</style>